package cn.wolfcode.p2p.website.controller;

import org.springframework.util.StreamUtils;

import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;

/**
 * Created by wolfcode on 2018/7/22.
 */
public class HttpUrlConnectionTest {
    public static void main(String[] args) throws Exception {
        //1.定义需要访问的地址
        URL url = new URL("https://way.jd.com/turing/turing");
        //2.通过url获取远程的连接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //3.设置请求的配置信息
        conn.setRequestMethod("GET");
        conn.setDoOutput(true);
        //4.给该地址拼接参数
        StringBuilder param = new StringBuilder(50);
        //?info=你是男的还是女的&loc=广东省广州市天河区棠下街道&userid=222&appkey=e50b3303a2fa65774b440c0f084a82b9
        param.append("info=").append("今晚打老虎")
                .append("&loc=").append("广东省广州市天河区棠下街道")
                .append("&userid=").append("222")
                .append("&appkey=").append("e50b3303a2fa65774b440c0f084a82b9");
        //把参数输出到对方服务器中
        conn.getOutputStream().write(param.toString().getBytes(Charset.forName("utf-8")));
        //发起连接
        conn.connect();
        //获取对方服务器给响应数据
        String respStr = StreamUtils.copyToString(conn.getInputStream(),Charset.forName("utf-8"));
        System.out.println(respStr);
    }
}
